const tjs = require('translation.js')
const logger = require('../utils/logger')
const totalInfoHandle = require('../utils/totalInfoHandle')
const {crawlerConfig} = require('../config')
const {encoding, retries, retryTimeout} = crawlerConfig

const c = require('./c')
const transRetry = async (content, url) => {
  let retriesLeft = 10
  return new Promise((resolve ,reject) => {
    resolve(content)

    // let fn = async () => {
    //   try {
    //     let data = await tjs
    //       .translate({
    //         text: content,
    //         from: 'th', // 文本的源语种
    //         to: 'zh-CN', // 文本的目标语种,
    //         api: 'baidu'
    //       })
    //     resolve(data.result[0])
    //   } catch (e) {
    //     if(retriesLeft === 0) {
    //       reject(e, url)
    //     } else {
    //       retriesLeft--
    //       console.log(`translagte ${content} retry ${retriesLeft} left`)
    //       fn()
    //     }
    //   }
    // }
    // fn()
  })
}

const transPromise = function (content, url = '', api = 'baidu') {
  return new Promise(function (resolve, reject) {
    if (content === null || content === undefined || content.length === 0) {
      resolve([])
    } else {
      let isArray = Array.isArray(content)
      if (isArray) {
        let arr = content.map(item => transPromise(item))
        Promise.all(arr).then(data => {
          resolve(data)
        }, err => {
          reject(err)
          logger.error(err, content.join(','), url)
        })
      } else {
        totalInfoHandle.add({
          type:4,
          url: url,
          info: content
        })

        transRetry(content, url).then(data=> {
          totalInfoHandle.addSuccess({
            type:4,
            url: url,
            info: content
          })
          resolve(data)
        }, err => {
          totalInfoHandle.addError({
            type:4,
            url: url,
            info: content,
            error: err
          })
          logger.error(err, content, url)
          reject(err)
        })

      }
    }
  });
};

const cPromise = url => {
  return new Promise((resolve, reject) => {
    try {
      if (url !== '' || url !== undefined || url !== null) {
        c.queue([{
          uri: url,
          encoding,
          retries,
          retryTimeout,
          callback: function (error, res, done) {
            if (error) {
              logger.error(url, error)
              totalInfoHandle.addError({
                type: 3,
                url
              })
	            reject(err)
            } else {
              if (res.$) {
                resolve(res.$)
              } else {
                resolve(res)
              }

              done();
              totalInfoHandle.addSuccess({
                type: 3,
                url
              })
            }
          }
        }]);
      } else {
	      resolve('')
        totalInfoHandle.addError({
          type: 3,
          url
        })
      }
    } catch (e) {
      reject(e)
      logger.error(e, url)
      totalInfoHandle.addError({
        type: 3,
        url
      })
    }
  })
}

module.exports = {
  transPromise,
  cPromise
}
